<!--
初始化
 -->
<template>
  <div class="container">
    <div id="cesiumContainer"> </div>
  </div>
</template>

<script>
  export default {
    name: "cesiumviewer",
    data() {
      return {
        viewer: {},
      }
    },
    mounted() {

      // this.LoadDx();
      // return

      var Cesium = this.Cesium;
      this.viewer = new Cesium.Viewer("cesiumContainer", {
        animation: false, // 是否显示动画控件
        homeButton: false, // 是否显示home键
        geocoder: false, // 是否显示地名查找控件
        baseLayerPicker: false, // 是否显示图层选择控件
        timeline: false, // 是否显示时间线控件
        fullscreenButton: true, // 是否全屏显示
        infoBox: true, // 是否显示点击要素之后显示的信息
        sceneModePicker: false, // 是否显示投影方式控件  三维/二维
        navigationInstructionsInitiallyVisible: false,
        navigationHelpButton: false, // 是否显示帮助信息控件
        orderIndependentTranslucency: false,
        shouldAnimate: true,
        scene3DOnly: false, // 每个几何实例将只能以3D渲染以节省GPU内存
        selectionIndicator: false // 取消点击有绿框
      });
      this.viewer._cesiumWidget._creditContainer.style.display = "none"; //隐藏ceisum标识
      //this.viewer.cesiumWidget.creditContainer.style.display = 'none'; //隐藏ceisum标识

      let viewer = this.viewer
      var scene = viewer.scene;
      // 用entity创建一个geometry
      // var entity = viewer.entities.add({
      //     rectangle: {
      //         coordinates: Cesium.Rectangle.fromDegrees(-100.0, 20.0, -90.0, 30.0),
      //         material: new Cesium.StripeMaterialProperty({
      //             evenColor: Cesium.Color.WHITE,
      //             oddColor: Cesium.Color.BLUE,
      //             repeat: 5 // 重复5条
      //         })
      //     }
      // });
      // for (var lon = -180.0; lon < 180.0; lon += 5.0) {
      //     for (var lat = -85.0; lat < 85.0; lat += 5.0) {
      //         viewer.entities.add({
      //             rectangle: new Cesium.RectangleGraphics({
      //                 coordinates: Cesium.Rectangle.fromDegrees(lon, lat, lon + 5.0, lat + 5.0),
      //                 material: new Cesium.ColorMaterialProperty(Cesium.Color.fromRandom({alpha: 0.5})),
      //                 outline: true,
      //                 outlineColor: Cesium.Color.WHITE,
      //                 outlineWidth: 1.5
      //             })
      //
      //         })
      //     }
      // }

      //
      // viewer.trackedEntity = entity;

      // var primitive = new Cesium.Primitive({
      //     geometryInstances: new Cesium.GeometryInstance({
      //         geometry: new Cesium.RectangleGeometry({
      //             rectangle: Cesium.Rectangle.fromDegrees(-100.0, 20.0, -90.0, 30.0)
      //         })
      //     }),
      //     appearance: new Cesium.MaterialAppearance({
      //         material: Cesium.Material.fromType(Cesium.Material.StripeType)
      //     })
      // });
      //
      // viewer.scene.primitives.add(primitive);

      var instances = [];
      //循环创建随机颜色的矩形
      for (var lon = -180.0; lon < 180.0; lon += 5.0) {
        for (var lat = -85.0; lat < 85.0; lat += 5.0) {
          instances.push(new Cesium.GeometryInstance({
            id: Cesium.Math.nextRandomNumber(),
            geometry: new Cesium.RectangleGeometry({
              rectangle: Cesium.Rectangle.fromDegrees(lon, lat, lon + 5.0, lat + 5.0),
              vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
            }),
            attributes: {
              color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromRandom({
                alpha: 0.5
              }))
            }
          }));
        }
      }

      // scene.primitives.add(new Cesium.Primitive({
      //   geometryInstances: instances,
      //   appearance: new Cesium.PerInstanceColorAppearance() //使用PerInstanceColorAppearance不同颜色来遮蔽每个实例
      // }));

      // //获取屏幕事件管理器
      // viewer.screenSpaceEventHandler.setInputAction(function(movement) {
      //   var pick = scene.pick(movement.endPosition);
      //   if (Cesium.defined(pick)) {
      //     console.log(pick.id);
      //   }
      // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      // 这样的写法自然是有优点也有缺点的
      //
      // 优点：
      //
      // 性能 - 当绘制大量静态图元时，直接使用几何形状可以将它们组合成单个几何体，以减少CPU开销并更好地利用GPU。并且组合是在网络上完成的，可以保持UI的响应。
      // 灵活性 - 基元组合几何和外观。通过解耦，我们可以独立地修改。我们可以添加与许多不同外观兼容的新几何体，反之亦然。
      // 低级访问 - 外观提供了接近于渲染器的访问，可以直接使用渲染器的所有细节(Appearances provide close-to-the-metal access to rendering without having to worry about all the details of using the Renderer directly)。外观使其易于：
      // 编写完整的GLSL顶点和片段着色器。
      // 使用自定义渲染状态。
      //
      // 缺点：
      //
      // 代码量增大，并且需要使用者对这方面有更深入的理解。
      // 组合几何可以使用静态数据，不一定是动态数据。
      // primitives 的抽象级别适合于映射应用程序;几何图形和外观的抽象层次接近传统的3D引擎(Primitives are at the level of abstraction appropriate for mapping apps; geometries and appearances have a level of abstraction closer to a traditional 3D engine)（感觉翻译的不太好的地方都给上了原文）

      this.Raining();
    },
    methods: {
      Raining() { //雨天，感觉有问题
        let scene = this.viewer.scene
        let viewer = this.viewer
        let Cesium = this.Cesium
        scene.debugShowFramesPerSecond = true;

        var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(114.0, 30.0));

        var minX = -1000.0;
        var maxX = 1000.0;
        var minY = -800.0;
        var maxY = 1000.0;
        var minZ = -500.0;
        var maxZ = 500.0;

        var rainCount = 100;
        var color = Cesium.Color.fromRandom({
          red: 0.75,
          green: 0.0,
          blue: 0.8,
          alpha: 1.0
        });
        for (var i = 0; i < rainCount; i++) {

          var x = Cesium.Math.randomBetween(minX, maxX);
          var y = Cesium.Math.randomBetween(minY, maxY);
          var z = Cesium.Math.randomBetween(minZ, maxZ);
          var height = Cesium.Math.randomBetween(800, 1000);
          var offset = new Cesium.Cartesian3(x, y, z);
          var position = Cesium.Cartesian3.add(new Cesium.Cartesian3(0.0, 0.0, height), offset, new Cesium
            .Cartesian3());
          var emitterMatrix = Cesium.Matrix4.fromTranslation(position, new Cesium.Matrix4());
          viewer.scene.primitives.add(new Cesium.ParticleSystem({
            image: '../../../static/models/rainy.png',
            // startColor: color.withAlpha(0.7),
            // endColor: color.withAlpha(0.0),
            life: 20,
            speed: Math.floor(Math.random() * 20 + 1),
            width: 6,
            rate: 1,
            height: 6,
            lifeTime: 16,
            loop: true,
            emitter: new Cesium.CircleEmitter(0.5),
            emitterModelMatrix: emitterMatrix,
            modelMatrix: modelMatrix,
            forces: [applyGravity]
          }))
        }

        function applyGravity(particle, dt) {
          var position = particle.position;
          var gravityVector = Cesium.Cartesian3.normalize(position, new Cesium.Cartesian3());
          Cesium.Cartesian3.multiplyByScalar(gravityVector, -100 * dt, gravityVector);
          particle.velocity = Cesium.Cartesian3.add(particle.velocity, gravityVector, particle.velocity);
        }

        var camera = viewer.scene.camera;
        var cameraOffset = new Cesium.Cartesian3(-600.0, 0.0, 0.0);
        camera.lookAtTransform(modelMatrix, cameraOffset);
      },

      LoadDx() { //影像和地形，有问题，url无法访问
        let Cesium = this.Cesium
        var viewer = new Cesium.Viewer('cesiumContainer', {
          baseLayerPicker: false,
          // Google
          // imageryProvider: new Cesium.UrlTemplateImageryProvider({
          //     url: 'http://www.google.cn/maps/vt?lyrs=s@716&x={x}&y={y}&z={z}'
          // })
          // ArcGIS
          // imageryProvider : new Cesium.ArcGisMapServerImageryProvider({
          //     // url : 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
          //     url : 'http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer'
          // }),
          // BingMaps
          // imageryProvider: new Cesium.BingMapsImageryProvider({
          //     url: 'https://dev.virtualearth.net',
          //     key: 'Ao42l-0u7fJXMmQSGY0_5zW6kfuHPeTtanya4rs8bItYH982UV42_xNccLDq70lY',
          //     mapStyle: Cesium.BingMapsStyle.AERIAL
          // })
          // OSM
          // imageryProvider: Cesium.createOpenStreetMapImageryProvider({
          //     url : 'https://a.tile.openstreetmap.org/'
          // })
          // imageryProvider: new Cesium.GoogleEarthEnterpriseImageryProvider({
          //     metadata : new Cesium.GoogleEarthEnterpriseMetadata({
          //         url:'http://www.earthenterprise.org/3d'
          //     })
          // })
          imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
            url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
            layer: "tdtBasicLayer",
            style: "default",
            format: "image/jpeg",
            tileMatrixSetID: "GoogleMapsCompatible",
            show: false
          })
        });

        //全球影像中文注记服务
        viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
          url: "http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg",
          layer: "tdtAnnoLayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",
          show: false
        }));

        // var blackMarble = viewer.imageryLayers.addImageryProvider(Cesium.createTileMapServiceImageryProvider({
        //     url : 'https://cesiumjs.org/tilesets/imagery/blackmarble',
        //     maximumLevel : 8,
        //     flipXY : true,
        //     credit : 'Black Marble imagery courtesy NASA Earth Observatory'
        // }));
        //
        // //50%透明度
        // blackMarble.alpha  = 0.8;
        // //两倍亮度
        // blackMarble.brightness = 2.0;

        // defaultAlpha 和 defaultBrightness 是 ImageryProvider的属性

        viewer.imageryLayers.addImageryProvider(new Cesium.SingleTileImageryProvider({ // 单张图片，适合雷达卫星图，视频贴图
          url: '../../../static/models/Cesium_Logo_Color_Overlay.png',
          rectangle: Cesium.Rectangle.fromDegrees(-75.0, 28.0, -67.0, 29.75)
        }));

        var terrainProvider = new Cesium.CesiumTerrainProvider({
          url: 'https://assets02.agi.com/stk-terrain/v1/tilesets/world/tiles',
          //请求水波纹效果
          requestWaterMask: true,
          //请求照明
          requestVertexNormals: true
        });
        viewer.terrainProvider = terrainProvider;

        //开启照明
        // viewer.scene.globe.enableLighting = true;
      }

    }
  }
</script>

<style scoped="scoped">
  .container {
    width: 100%;
    height: 100%;
  }

  #cesiumContainer {
    width: 100%;
    height: 100%;
    position: absolute;
    margin: 0;
    padding: 0;
    /*  overflow: hidden; */
  }
</style>
